<?php

namespace app\admin\controller;

use app\admin\logic\ExportQuestionLogic;
use app\admin\logic\ImportQuestionLogic;
use app\common\controller\Backend;
use app\common\exception\BusinessException;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 试卷管理
 *
 * @icon fa fa-circle-o
 */
class Coursepaper extends Backend
{

    /**
     * Coursepaper模型对象
     * @var \app\admin\model\Coursepaper
     */
    protected $model = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Coursepaper;

    }


    /**
     * 试卷列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['course', 'category'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if (empty($params['course_id'])) {
                        throw new BusinessException('请选择关联课程');
                    }
                    if (empty($params['category_id'])) {
                        throw new BusinessException('请选择关联分类');
                    }
                    
                    // 查询关联分类的is_need_vip字段，并同步到试卷
                    $categoryModel = new \app\admin\model\Questioncategory;
                    $category = $categoryModel->where('id', $params['category_id'])->find();
                    if (!$category) {
                        throw new BusinessException('未找到关联分类');
                    }
                    $params['is_need_vip'] = $category['is_need_vip'];
                    
                    $params['create_time'] = time();
                    $params['update_time'] = time();
                    $result = $this->model->allowField(true)->save($params);


                    // 更新分类信息
                    if ($result !== false) {
                        $categoryModel = new \app\admin\model\Coursequestioncategory();
                        $categoryModel->setQuestionCountById($params['category_id']);
                    }



                    Db::commit();
                    

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                    
                    // 更新分类信息
                    if ($result !== false) {
                        $categoryModel = new \app\admin\model\Coursequestioncategory();
                        $categoryModel->setQuestionCountById($params['category_id'] ?? $row['category_id']);
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        $this->view->assign("categoryParams", 'data-params={"custom[course_id]":["eq","' . $row['course_id'] . '"]}');
        return $this->view->fetch();
    }

    /**
     * 导入题目
     */
    public function importQuestion($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['paper_id'])) {
                $this->error(__('导入试卷不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            try {
                Db::startTrans();
                (new ImportQuestionLogic())->import($row['course_id'], $params['paper_id'], $params['attachment']);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('导入成功');
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 导出题目
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function exportQuestion($ids = null)
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['paper_id'])) {
                $this->error(__('导出试卷不得为空'));
            }

            // 查询试卷
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            try {
                $filePath = (new ExportQuestionLogic())->export([$row['course_id']], [$params['paper_id']]);
            } catch (\Exception $exception) {
                $this->error(__($exception->getMessage()));
            }
            $this->success('导出成功', null, $filePath);
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 导出电子版
     */
    public function exportWord($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['id'])) {
                $this->error(__('导出试卷不得为空'));
            }
            
            // 检查应用场景参数
            if (!isset($params['scene']) || !in_array($params['scene'], [1, 2])) {
                $this->error(__('请选择正确的应用场景'));
            }

            try {
                $logic = new \app\admin\logic\GeneratePaperDocument();
                $result = $logic->invoke($params['id'], $params['scene']); 
            } catch (\Exception $exception) {
                $this->error(__($exception->getMessage()));
            }
            $this->success('导出成功', null, $result);
        }
        $this->assign('ids', $ids);
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 删除试卷
     * @param string $ids 试卷ID
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        // 检查权限
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        // 获取试卷列表
        $list = $this->model->where($pk, 'in', $ids)->select();
        if (!$list) {
            $this->error(__('No Results were found'));
        }
        
        $count = 0;
        Db::startTrans();
        try {
            // 提取ID
            $categoryIds = [];
            $allPaperIds = [];
            foreach ($list as $item) {
                $categoryIds[] = $item['category_id'];
                $allPaperIds[] = $item['id'];
            }

            // 去重ID
            $categoryIds = array_unique($categoryIds);
            $allPaperIds = array_unique($allPaperIds);
            
            // 删除试卷
            foreach ($list as $item) {
                $count += $item->delete();
            }
            
            // 删除关联题目
            (new \app\admin\model\Question())->where(['extend_id' => ['in', $allPaperIds]])->delete();
            
            // 更新分类题目数量
            $categoryModel = new \app\admin\model\Coursequestioncategory();
            foreach ($categoryIds as $categoryId) {
                $categoryModel->setQuestionCountById($categoryId);
            }
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $action = $this->request->post("action");
        if ($ids) {
            if ($action == 'clearquestion') {
                // 同步删除题目
                $where = ['type' => 4, 'extend_id' => ['in', $ids]];
                $model = new \app\admin\model\Question();
                $model->where($where)->delete();
            }
        }
        $this->success();
    }

    /**
     * 清空题目
     */
    public function clearquestion($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $questionModel = new \app\admin\model\Question();
                    $questionModel->where('extend_id', $v->id)->delete();
                    $count++;
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 批量标记为会员试卷
     */
    public function batchsetmemberpaper()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $ids = $params['ids'];
            $is_need_vip = isset($params['is_need_vip']) ? intval($params['is_need_vip']) : 0;
            if (empty($ids)) {
                $this->error(__('Parameter %s can not be empty', 'ids'));
            }
            
            $count = 0;
            Db::startTrans();
            try {
                $list = $this->model->where('id', 'in', $ids)->select();
                foreach ($list as $index => $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save(['is_need_vip' => $is_need_vip]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        
        $ids = $this->request->get('ids');
        $this->view->assign('ids', $ids);
        return $this->view->fetch();
    }
}
